package com.example.lib5.search.test;

import java.util.ArrayList;
import java.util.List;

public class BinarySearchB {
    public static void main(String[] args) {
        int[] arr={1,8,10,89,1000,1000,1000,1000,1024};
//        int index=binarySearch(arr,0,arr.length-1,1);
//        System.out.println(index);
        List<Integer> list = binarySearch2(arr, 0, arr.length - 1, 1000);
        System.out.println(list.toString());
    }

    private static int binarySearch(int[] arr, int left, int right, int findValue) {
        if (left>right) {
            return -1;
        }
        //获取中间值
        int midIndex = (left + right) / 2;
        int midValue=arr[midIndex];
        //与中间值进行比较，判断往哪里遍历
        if (findValue>midValue) {
            return binarySearch(arr,midIndex+1,right,findValue);
        }else if (findValue<midValue){
            return binarySearch(arr,left,midIndex-1,findValue);
        }else {
            return midIndex;
        }
    }
    private static List<Integer> binarySearch2(int[] arr, int left, int right, int findValue) {
        if (left>right) {
            return null;
        }
        //获取中间值
        int midIndex = (left + right) / 2;
        int midValue=arr[midIndex];
        //与中间值进行比较，判断往哪里遍历
        if (findValue>midValue) {
            return binarySearch2(arr,midIndex+1,right,findValue);
        }else if (findValue<midValue){
            return binarySearch2(arr,left,midIndex-1,findValue);
        }else {
            List<Integer> list=new ArrayList<>();
            //找到那个值后，向左遍历，然后向右遍历即可

            int temp=midIndex-1;
            while (true){
                //跳出的条件
                if (temp<0||arr[temp]!=findValue){
                    break;
                }
                list.add(temp);
                temp--;

            }
            list.add(midIndex);
            temp=midIndex+1;
            while (true){
                //跳出的条件
                if (temp>arr.length-1||arr[temp]!=findValue){
                    break;
                }
                list.add(temp);
                temp++;

            }
            return list;
        }
    }
}
